import { apiClient } from "./index";
import type { User, LoginForm, RegisterForm } from "@/types";
import { LocalStorage } from "@/utils/storage";

export interface AuthResponse {
  user: User;
  token: string;
}

export class AuthAPI {
  /**
   * 用户登录
   */
  static async login(loginForm: LoginForm) {
    try {
      const response = await apiClient.post<AuthResponse>("/auth/login", {
        emailOrUsername: loginForm.email,
        password: loginForm.password,
      });

      if (response.success && response.data) {
        // 保存 token
        apiClient.setToken(response.data.token);

        return {
          success: true,
          user: response.data.user,
          token: response.data.token,
          message: response.message,
        };
      }

      return {
        success: false,
        message: response.message || "登录失败",
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "登录失败",
      };
    }
  }

  /**
   * 用户注册
   */
  static async register(registerForm: RegisterForm) {
    try {
      const response = await apiClient.post<AuthResponse>("/auth/register", {
        email: registerForm.email,
        username: registerForm.nickname, // 后端使用 username 字段
        password: registerForm.password,
      });

      if (response.success && response.data) {
        // 保存 token
        apiClient.setToken(response.data.token);

        return {
          success: true,
          user: response.data.user,
          token: response.data.token,
          message: response.message,
        };
      }

      return {
        success: false,
        message: response.message || "注册失败",
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "注册失败",
      };
    }
  }

  /**
   * 获取当前用户信息
   */
  static async getProfile() {
    try {
      const response = await apiClient.get<{ user: User }>("/auth/me");

      if (response.success && response.data && response.data.user) {
        return {
          success: true,
          user: response.data.user,
          message: response.message || "获取用户信息成功",
        };
      }

      return {
        success: false,
        message: response.message || "获取用户信息失败",
      };
    } catch (error) {
      console.error("获取用户信息失败:", error);
      return {
        success: false,
        message: (error as Error).message || "获取用户信息失败",
      };
    }
  }

  /**
   * 用户登出
   */
  static async logout() {
    try {
      await apiClient.post("/auth/logout");

      // 清除本地 token
      apiClient.setToken(null);

      return {
        success: true,
        message: "退出登录成功",
      };
    } catch (error) {
      // 即使请求失败，也要清除本地 token
      apiClient.setToken(null);

      return {
        success: true,
        message: "退出登录成功",
      };
    }
  }

  /**
   * 修改密码
   */
  static async changePassword(oldPassword: string, newPassword: string) {
    try {
      const response = await apiClient.put("/auth/change-password", {
        oldPassword,
        newPassword,
      });

      return {
        success: response.success,
        message: response.message,
      };
    } catch (error) {
      return {
        success: false,
        message: (error as Error).message || "修改密码失败",
      };
    }
  }

  /**
   * 检查登录状态
   */
  static async checkAuthStatus() {
    // 使用LocalStorage工具类获取token（支持localStorage和sessionStorage）
    const token = LocalStorage.getTokenFromStorage();
    if (!token) {
      return {
        success: false,
        message: "未登录",
      };
    }

    // 设置 token 到 API 客户端
    apiClient.setToken(token);

    try {
      // 尝试获取用户信息来验证 token 是否有效
      const response = await apiClient.get<{ user: User }>("/auth/me");

      if (response.success && response.data && response.data.user) {
        return {
          success: true,
          user: response.data.user,
          message: response.message || "获取用户信息成功",
        };
      }

      return {
        success: false,
        message: response.message || "获取用户信息失败",
      };
    } catch (error) {
      console.error("检查登录状态失败:", error);
      // 如果验证失败，清理token
      apiClient.setToken(null);
      return {
        success: false,
        message: "登录状态已失效",
      };
    }
  }
}
